import numpy as np
import csv
from datetime import datetime
from time import strftime
import arcpy
import os


def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def delete_shapefiles(temp_path):
    # e.g. temp_path = "c:/temp/a.shp"    a.dbf, a.prj, a.sbn, a.sbx, a.shp, a.shp.xml, a.shx will be deleted
    temp_suffix = ["dbf", "prj", "sbn", "sbx", "shp", "shp.xml", "shx"]
    if os.path.exists(temp_path):
        for item in temp_suffix:
            if os.path.exists(temp_path[:-3] + item):
                os.remove(temp_path[:-3] + item)
    else:
        print temp_path + " does not exist!"
        return 

#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()

    filepath = 'C:/_DATA/migration_census_2000/7-09-2012/irs_state_oldExp.csv'
    data = build_data_list(filepath)

    filepath = 'C:/_DATA/migration_census_2000/irs_state_circle.csv'
    tempdata = build_data_list(filepath)
    state_id = {}
    for item in tempdata:
        state_id[int(item[1])] = int(item[0])
    
    centroidCSV = 'C:/_DATA/migration_census_2000/state_census_centroid.csv'
    cenroid = build_data_list(centroidCSV)

    workspace = 'C:/_DATA/migration_census_2000/7-09-2012/'
    arcpy.workspace = workspace
    shapefielName = 'irs_state_oldExp.shp'
    shapefile = workspace + shapefielName

    if os.path.exists(shapefile):
        delete_shapefiles(shapefile)
    arcpy.CreateFeatureclass_management(workspace, shapefielName, 'POLYLINE')
    #coordsys = "C:/Program Files (x86)/ArcGIS/Desktop10.0/Coordinate Systems/Projected Coordinate Systems/Continental/North America/North America Albers Equal Area Conic.prj"
    coordsys = 'C:/_DATA/migration_census_2000/continental_cnty_simplified.prj'
    arcpy.DefineProjection_management(shapefile, coordsys)

    cur = arcpy.InsertCursor(shapefile)
   
    pnt = arcpy.CreateObject('point')
    
    for item in data:
        array = arcpy.CreateObject('Array')
        print state_id[int(item[2])], state_id[int(item[3])]
        pnt.X = cenroid[state_id[int(item[3])],0]
        pnt.Y = cenroid[state_id[int(item[3])],1]
        array.add(pnt)
        pnt.X = cenroid[state_id[int(item[2])],0]
        pnt.Y = cenroid[state_id[int(item[2])],1]
        array.add(pnt)
        row = cur.newRow()
        row.Shape = array
        cur.insertRow(row)
        #array.removeAll
    #arcpy.addField(shapefile, ', 'LONG')


    #np.savetxt(filepath[:-4] + '_unique.csv', output, delimiter=',', fmt = '%i')